<template>
  <div class="recommend-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        <BulbOutlined class="title-icon" />
        个性化推荐
      </h1>
      <p class="page-subtitle">基于您的兴趣为您推荐精彩内容</p>
    </div>

    <!-- 用户兴趣分析 -->
    <div class="interest-analysis">
      <div class="analysis-card">
        <div class="card-header">
          <UserOutlined class="card-icon" />
          <span class="card-title">您的兴趣偏好</span>
        </div>
        <div class="interest-tags">
          <a-tag
            v-for="interest in userInterests"
            :key="interest.tag"
            :color="interest.color"
            class="interest-tag"
          >
            {{ interest.tag }} ({{ interest.weight }}%)
          </a-tag>
        </div>
        <div class="analysis-tip">
          <InfoCircleOutlined />
          <span>系统会根据您的浏览、点赞、收藏行为持续优化推荐</span>
        </div>
      </div>
    </div>

    <!-- 推荐筛选 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-label">推荐类型：</div>
        <div class="filter-content">
          <a-radio-group v-model:value="recommendType" @change="handleRecommendTypeChange">
            <a-radio-button value="all">全部推荐</a-radio-button>
            <a-radio-button value="similar">相似图片</a-radio-button>
            <a-radio-button value="trending">热门推荐</a-radio-button>
            <a-radio-button value="new">最新推荐</a-radio-button>
          </a-radio-group>
        </div>
      </div>

      <div class="filter-row">
        <div class="filter-label">分类筛选：</div>
        <div class="filter-content">
          <a-select
            v-model:value="selectedCategory"
            placeholder="选择分类"
            style="width: 200px"
            allowClear
            @change="handleCategoryChange"
          >
            <a-select-option value="">全部分类</a-select-option>
            <a-select-option v-for="category in categories" :key="category" :value="category">
              {{ category }}
            </a-select-option>
          </a-select>
        </div>
      </div>

      <div class="filter-row">
        <div class="filter-label">推荐数量：</div>
        <div class="filter-content">
          <a-select v-model:value="recommendLimit" style="width: 120px" @change="handleLimitChange">
            <a-select-option :value="10">10张</a-select-option>
            <a-select-option :value="20">20张</a-select-option>
            <a-select-option :value="50">50张</a-select-option>
            <a-select-option :value="100">100张</a-select-option>
          </a-select>
        </div>
      </div>
    </div>

    <!-- 推荐内容展示 -->
    <div class="recommend-content">
      <a-spin :spinning="loading" tip="正在为您推荐...">
        <!-- 网格视图 -->
        <div class="grid-view">
          <div v-for="item in recommendList" :key="item.id" class="grid-item">
            <div
              class="image-card"
              :class="{ 'is-selected': selectedImages.includes(item) }"
              @click="handleImageClick(item)"
            >
              <div class="image-wrapper">
                <img
                  :src="IMAGE_PREFIX + (item.thumbnailUrl || '')"
                  :alt="item.name"
                  class="image"
                  @error="handleImageError"
                />
                <div class="image-overlay">
                  <div class="overlay-content">
                    <EyeOutlined @click.stop="showImageDetails(item)" />
                  </div>
                </div>
                <!-- 推荐理由标签 -->
                <div class="recommend-reason" v-if="item.recommendReason">
                  <BulbOutlined />
                  <span>{{ item.recommendReason }}</span>
                </div>
              </div>
              <div class="image-info">
                <div class="image-name" v-html="highlightKeyword(item.name).html"></div>
                <div class="image-meta">
                  <span class="category">{{ item.category }}</span>
                  <span class="size">{{ (Number(item.picSize) / 1024).toFixed(2) }} KB</span>
                </div>
                <div class="image-tags">
                  <a-tag
                    v-for="tag in item.tags ? JSON.parse(item.tags) : []"
                    :key="tag"
                    size="small"
                  >
                    {{ tag }}
                  </a-tag>
                </div>
                <div class="image-action-bar">
                  <span class="icon-btn" @click.stop="handleLike(item)">
                    <template v-if="item.liked">
                      <HeartFilled style="color: #f5222d" />
                    </template>
                    <template v-else>
                      <HeartOutlined />
                    </template>
                    {{ formatCount(item.likeCount) }}
                  </span>
                  <span class="icon-btn" @click.stop="handleFavorite(item)">
                    <template v-if="item.favorited">
                      <StarFilled style="color: #faad14" />
                    </template>
                    <template v-else>
                      <StarOutlined />
                    </template>
                    {{ formatCount(item.favoriteCount) }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <a-pagination
            v-model:current="currentPage"
            v-model:pageSize="pageSize"
            :total="total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :show-total="(total, range) => `共 ${total} 项，当前第 ${range[0]}-${range[1]} 项`"
            @change="handlePageChange"
            @showSizeChange="handlePageSizeChange"
          />
        </div>
      </a-spin>
    </div>

    <!-- 图片详情模态框 -->
    <PreviewModal
      v-model:visible="previewVisible"
      :image="selectedImage"
      @like="handleLike"
      @favorite="handleFavorite"
      @download="handleDownload"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { message } from 'ant-design-vue'
  import {
    BulbOutlined,
    UserOutlined,
    InfoCircleOutlined,
    HeartOutlined,
    HeartFilled,
    StarOutlined,
    StarFilled,
    EyeOutlined,
  } from '@ant-design/icons-vue'
  import {
    getPersonalizedRecommendUsingGet,
    getCategoriesUsingGet1,
    likePictureUsingPost1,
    cancelLikePictureUsingPost1,
    batchAddFavoriteUsingPost1,
    batchCancelFavoriteUsingPost1,
    downloadImageUsingGet1,
    recordUserBehaviorUsingPost,
  } from '@/api/tupianguanlijiekou'
  import { useLoginUserStore } from '@/stores/useLoginUserStore'
  import PreviewModal from '@/components/PreviewModal.vue'

  // 常量
  const IMAGE_PREFIX = import.meta.env.VITE_API_BASE_URL + '/api/file/'

  // 状态管理
  const loginUserStore = useLoginUserStore()

  // 响应式数据
  const loading = ref(false)
  const recommendList = ref<any[]>([])
  const categories = ref<string[]>([])
  const currentPage = ref(1)
  const pageSize = ref(20)
  const total = ref(0)
  const selectedImages = ref<any[]>([])

  // 筛选参数
  const recommendType = ref<'all' | 'similar' | 'trending' | 'new'>('all')
  const selectedCategory = ref<string>('')
  const recommendLimit = ref(20)

  // 用户兴趣数据
  const userInterests = ref([
    { tag: '科技', weight: 85, color: 'blue' },
    { tag: '风景', weight: 72, color: 'green' },
    { tag: '人物', weight: 68, color: 'orange' },
    { tag: '创意', weight: 65, color: 'purple' },
    { tag: '实用', weight: 58, color: 'cyan' },
  ])

  // 预览相关
  const previewVisible = ref(false)
  const selectedImage = ref<any>(null)

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const res = await getCategoriesUsingGet1()
      if (res.data.code === 200) {
        categories.value = res.data.data || []
      }
    } catch (error) {
      console.error('获取分类失败:', error)
    }
  }

  // 获取推荐数据
  const fetchRecommendData = async () => {
    loading.value = true
    try {
      const params = {
        userId: loginUserStore.loginUser?.id,
        limit: recommendLimit.value,
        category: selectedCategory.value,
        page: currentPage.value,
        pageSize: pageSize.value,
      }

      const res = await getPersonalizedRecommendUsingGet(params)
      if (res.data.code === 200) {
        recommendList.value = res.data.data?.records || []
        total.value = res.data.data?.total || 0
      } else {
        message.error(res.data.message || '获取推荐失败')
      }
    } catch (error) {
      console.error('获取推荐失败:', error)
      message.error('获取推荐失败')
    } finally {
      loading.value = false
    }
  }

  // 事件处理
  const handleRecommendTypeChange = () => {
    currentPage.value = 1
    fetchRecommendData()
  }

  const handleCategoryChange = () => {
    currentPage.value = 1
    fetchRecommendData()
  }

  const handleLimitChange = () => {
    currentPage.value = 1
    fetchRecommendData()
  }

  const handlePageChange = (page: number) => {
    currentPage.value = page
    fetchRecommendData()
  }

  const handlePageSizeChange = (current: number, size: number) => {
    pageSize.value = size
    currentPage.value = 1
    fetchRecommendData()
  }

  // 图片操作
  const handleLike = async (item: any) => {
    if (!loginUserStore.loginUser?.id) {
      message.warning('请先登录')
      return
    }

    try {
      if (item.liked) {
        await cancelLikePictureUsingPost1(item.id)
        item.liked = false
        item.likeCount = Math.max(0, (item.likeCount || 1) - 1)
        message.success('取消点赞成功')
      } else {
        await likePictureUsingPost1(item.id)
        item.liked = true
        item.likeCount = (item.likeCount || 0) + 1
        message.success('点赞成功')
      }

      // 记录用户行为
      await recordUserBehaviorUsingPost({
        pictureId: item.id,
        userId: loginUserStore.loginUser.id,
        behaviorType: item.liked ? 'like' : 'view',
      })
    } catch (error) {
      console.error('操作失败:', error)
      message.error('操作失败')
    }
  }

  const handleFavorite = async (item: any) => {
    if (!loginUserStore.loginUser?.id) {
      message.warning('请先登录')
      return
    }

    try {
      if (item.favorited) {
        await batchCancelFavoriteUsingPost1(item.id)
        item.favorited = false
        item.favoriteCount = Math.max(0, (item.favoriteCount || 1) - 1)
        message.success('取消收藏成功')
      } else {
        await batchAddFavoriteUsingPost1(item.id)
        item.favorited = true
        item.favoriteCount = (item.favoriteCount || 0) + 1
        message.success('收藏成功')
      }

      // 记录用户行为
      await recordUserBehaviorUsingPost({
        pictureId: item.id,
        userId: loginUserStore.loginUser.id,
        behaviorType: item.favorited ? 'favorite' : 'view',
      })
    } catch (error) {
      console.error('操作失败:', error)
      message.error('操作失败')
    }
  }

  const handleDownload = async (item: any) => {
    try {
      await downloadImageUsingGet1({ pictureId: item.id })
      message.success('下载成功')

      // 记录下载行为
      if (loginUserStore.loginUser?.id) {
        await recordUserBehaviorUsingPost({
          pictureId: item.id,
          userId: loginUserStore.loginUser.id,
          behaviorType: 'download',
        })
      }
    } catch (error) {
      console.error('下载失败:', error)
      message.error('下载失败')
    }
  }

  const handleImageClick = (item: any) => {
    const index = selectedImages.value.findIndex(img => img.id === item.id)
    if (index > -1) {
      selectedImages.value.splice(index, 1)
    } else {
      selectedImages.value.push(item)
    }
  }

  const showImageDetails = (item: any) => {
    selectedImage.value = item
    previewVisible.value = true

    // 记录浏览行为
    if (loginUserStore.loginUser?.id) {
      recordUserBehaviorUsingPost({
        pictureId: item.id,
        userId: loginUserStore.loginUser.id,
        behaviorType: 'view',
      })
    }
  }

  const handleImageError = (event: Event) => {
    const img = event.target as HTMLImageElement
    img.src = '/src/assets/default_avatar.png'
  }

  // 工具函数
  const formatCount = (count: number) => {
    if (!count) return '0'
    if (count >= 10000) {
      return (count / 10000).toFixed(1) + 'w'
    }
    return count.toString()
  }

  const highlightKeyword = (text: string) => {
    return {
      html: text,
      matched: false,
    }
  }

  // 生命周期
  onMounted(() => {
    fetchCategories()
    fetchRecommendData()
  })
</script>

<style scoped>
  .recommend-container {
    padding: 24px;
    background: #f5f5f5;
    min-height: 100vh;
  }

  .page-header {
    text-align: center;
    margin-bottom: 32px;
  }

  .page-title {
    font-size: 32px;
    font-weight: bold;
    color: #1890ff;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
  }

  .title-icon {
    font-size: 36px;
  }

  .page-subtitle {
    font-size: 16px;
    color: #666;
    margin: 0;
  }

  .interest-analysis {
    margin-bottom: 24px;
  }

  .analysis-card {
    background: white;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
  }

  .card-icon {
    font-size: 20px;
    color: #1890ff;
  }

  .card-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .interest-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 16px;
  }

  .interest-tag {
    font-size: 14px;
    padding: 4px 12px;
  }

  .analysis-tip {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #666;
    font-size: 14px;
  }

  .filter-section {
    background: white;
    padding: 24px;
    border-radius: 8px;
    margin-bottom: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .filter-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }

  .filter-row:last-child {
    margin-bottom: 0;
  }

  .filter-label {
    width: 100px;
    font-weight: 500;
    color: #333;
  }

  .filter-content {
    flex: 1;
  }

  .recommend-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .grid-view {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    padding: 24px;
  }

  .grid-item {
    transition: all 0.3s;
  }

  .image-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    cursor: pointer;
    position: relative;
  }

  .image-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  }

  .image-card.is-selected {
    border: 2px solid #1890ff;
  }

  .image-wrapper {
    position: relative;
    width: 100%;
    height: 200px;
    overflow: hidden;
  }

  .image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s;
  }

  .image-card:hover .image {
    transform: scale(1.05);
  }

  .image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
  }

  .image-card:hover .image-overlay {
    opacity: 1;
  }

  .overlay-content {
    color: white;
    font-size: 24px;
  }

  .recommend-reason {
    position: absolute;
    top: 8px;
    left: 8px;
    background: rgba(24, 144, 255, 0.9);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .image-info {
    padding: 16px;
  }

  .image-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .image-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
  }

  .category {
    background: #1890ff;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }

  .size {
    color: #666;
    font-size: 12px;
  }

  .image-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    margin-bottom: 12px;
  }

  .image-action-bar {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .icon-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    transition: color 0.3s;
  }

  .icon-btn:hover {
    color: #1890ff;
  }

  .pagination-wrapper {
    padding: 24px;
    text-align: center;
    border-top: 1px solid #f0f0f0;
  }

  @media (max-width: 768px) {
    .recommend-container {
      padding: 16px;
    }

    .grid-view {
      grid-template-columns: 1fr;
      gap: 16px;
      padding: 16px;
    }

    .filter-row {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }

    .filter-label {
      width: auto;
    }
  }
</style>
